package org.imaginedays.androidall.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.imaginedays.androidall.R;
import org.imaginedays.androidall.app.AndroidAllApp;

import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;

public class UnzipFromAssetsACT extends Activity {

	String location = Environment.getExternalStorageDirectory() + "/unzipped/";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.unzip);

	}

	public void unzip(View v) {
//		String oldVersionDirName = checkOldVersion();
//		Log.e(AndroidAllApp.TAG, "oldVersionDirName: " + oldVersionDirName);
//		 deleteOldVersionDir(oldVersionDirName);
//		System.out.println(System.currentTimeMillis());
		long begin = System.currentTimeMillis();
		copyFileOrDir("gonglue.1.0.0");
//		unZip("gonglue.1.0.2.zip", getFilesDir().getAbsolutePath()+"/gonglue.1.0.2");
		long end = System.currentTimeMillis();
		Log.e(AndroidAllApp.TAG, formatLongToTimeStr((long) (end - begin)));
//		Log.e(AndroidAllApp.TAG, "" + getFilesDir().list().length);
		String[] fileList = getFilesDir().list();
//		Log.e(AndroidAllApp.TAG, "fileListLength: " + fileList.length);
//		// 判断目录下是否包含攻略的目录
		if (fileList.length > 0) {
			for (int i = 0; i < fileList.length; i++) {
				Log.e(AndroidAllApp.TAG, "fileName: " + fileList[i]);
			}
		}
//		
//		String path = getFilesDir() + File.separator + "gl";
		// delAllFile(path);
//			deleteDirectory(new File(path));
//		delFolder(path);
		Log.e(AndroidAllApp.TAG, "" + getFilesDir().list().length);
	}
	
	private void copyFileOrDir(String path) {
	    AssetManager assetManager = this.getAssets();
	    String assets[] = null;
	    try {
	        assets = assetManager.list(path);
	        if (assets.length == 0) {
	            copyFile(path);
	        } else {
	            String fullPath = this.getFilesDir()+"/" + path;
	            File dir = new File(fullPath);
	            if (!dir.exists())
	                dir.mkdir();
	            for (int i = 0; i < assets.length; ++i) {
	                copyFileOrDir(path + "/" + assets[i]);
	            }
	        }
	    } catch (IOException ex) {
	        Log.e("tag", "I/O Exception", ex);
	    }
	}

	private void copyFile(String filename) {
	    AssetManager assetManager = this.getAssets();
	    InputStream in = null;
	    OutputStream out = null;
	    try {
	        in = assetManager.open(filename);
	        String newFileName = this.getFilesDir()+ "/" + filename;
	        out = new FileOutputStream(newFileName);

	        byte[] buffer = new byte[1024];
	        int read;
	        while ((read = in.read(buffer)) != -1) {
	            out.write(buffer, 0, read);
	        }
	        in.close();
	        in = null;
	        out.flush();
	        out.close();
	        out = null;
	    } catch (Exception e) {
	        Log.e("tag", e.getMessage());
	    }

	}
	

	  private String checkOldVersion() {
			String[] fileList = this.getFilesDir().list();
			int size = fileList.length;
			ArrayList<String> fileNameList = new ArrayList<String>();
			if (size >= 2) {
				for (String versionDirName : fileList) {
					if (versionDirName.startsWith("gonglue.")) {
						fileNameList.add(versionDirName);
					}
				}

			}
			return getOldVersionDir(fileNameList);
		}

		private boolean deleteOldVersionDir(String versionDirName) {
			String path =this.getFilesDir() + File.separator
					+ versionDirName;
			return deleteDirectory(new File(path));
		}

		public boolean deleteDirectory(File path) {
			if (path.exists()) {
				File[] files = path.listFiles();
				for (int i = 0; i < files.length; i++) {
					if (files[i].isDirectory()) {
						deleteDirectory(files[i]);
					} else {
						files[i].delete();
					}
				}
			}
			return (path.delete());
		}

		private String getOldVersionDir(ArrayList<String> fileNameList) {
			int first = getInt(fileNameList.get(0).substring(
					"gonglue".length()));
			int tow = getInt(fileNameList.get(1).substring(
					"gonglue".length()));
			if (first > tow) {
				return fileNameList.get(1);
			} else {
				return fileNameList.get(0);
			}
		}

		public int getInt(String str) {
			return Integer.valueOf(str.replace(".", ""));
		}

	  
	  public String formatLongToTimeStr(Long l) {
			String str = "";
			int hour = 0;
			int minute = 0;
			int second = 0;

			second = l.intValue() / 1000;

			if (second > 60) {
				minute = second / 60;
				second = second % 60;
			}
			if (minute > 60) {
				hour = minute / 60;
				minute = minute % 60;
			}
			return (hour + "小时" + minute + "分钟" + second + "秒");
		}


	public void unZip(String zipFileName, String outputDirectory) {
		try {
//			ZipInputStream in = new ZipInputStream(getAssets()
//					.open(zipFileName));
			ZipInputStream in = new ZipInputStream(new FileInputStream(new File(Environment.getExternalStorageDirectory()+"/"+zipFileName)));
			// 获取ZipInputStream中的ZipEntry条目，一个zip文件中可能包含多个ZipEntry，
			// 当getNextEntry方法的返回值为null，则代表ZipInputStream中没有下一个ZipEntry，
			// 输入流读取完成；
			ZipEntry entry = in.getNextEntry();
			
			while (entry != null) {
				Log.e(AndroidAllApp.TAG, "name: "+entry.getName());
				// 创建以zip包文件名为目录名的根目录
				File file = new File(outputDirectory);
				file.mkdir();
				if (entry.isDirectory()) {

					String name = entry.getName();

					name = name.substring(0, name.length() - 1);

					file = new File(outputDirectory + File.separator + name);
					file.mkdir();

				} else {
					file = new File(outputDirectory + File.separator
							+ entry.getName());
					file.createNewFile();
					FileOutputStream out = new FileOutputStream(file);
					int b;
					while ((b = in.read()) != -1) {
						out.write(b);
					}
					out.close();
				}
				// 读取下一个ZipEntry
				entry = in.getNextEntry();

			}
			in.close();
			Log.e(AndroidAllApp.TAG, "done");

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
	}


	/**
	 * 删除文件夹
	 * 
	 * @param filePathAndName
	 *            String 文件夹路径及名称 如c:/fqf
	 * @param fileContent
	 *            String
	 * @return boolean
	 */
	public void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹

		} catch (Exception e) {
			System.out.println("删除文件夹操作出错");
			e.printStackTrace();

		}
	}

	/**
	 * 删除文件夹里面的所有文件
	 * 
	 * @param path
	 *            String 文件夹路径 如 c:/fqf
	 */
	public void delAllFile(String path) {
		File file = new File(path);
		if (!file.exists()) {
			return;
		}
		if (!file.isDirectory()) {
			return;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
			}
		}
	}

}
